/*
********************************************************************************
*
*	file : hal
*
********************************************************************************
*/
#include "bsp.h"
#include "pincfg.h"
#include "dataproc.h"
#include "app_update.h"

#define flash_unlock HAL_FLASH_Unlock
#define flash_lock HAL_FLASH_Lock

/*******************************************************************************
 * @brief  ap_flash_read
 * \param[in] none
 * \retval: none
 *******************************************************************************/
uint8_t ap_flash_read(uint32_t addr, uint32_t len, uint8_t *pdat)
{
    uint32_t *p32;

    p32 = (uint32_t *)pdat;

    len >>= 2;

    while (len--)
    {
        *p32++ = inpw(addr);
        addr += 4;
    }

    return 0;
}

/*******************************************************************************
 * @brief  ap_flash_write
 * \param[in] none
 * \retval: none
 *******************************************************************************/
uint8_t ap_flash_write(uint32_t addr, uint32_t len, uint8_t *pdat)
{
    uint32_t *p32, index;

    p32 = (uint32_t *)pdat;

    flash_unlock();

	FLASH->SR |= FLASH_SR_PGAERR | FLASH_SR_PGPERR | FLASH_SR_PGSERR;
	
    // 编程，逆序
    index = len >> 2;

    while (index--)
    {
        HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, addr + index * 4, p32[index]);
    }

    flash_lock();

    return 0;
}

/*******************************************************************************
 * @brief  ap_flash_erase
 * \param[in] none
 * \retval: none
 *******************************************************************************/
uint8_t ap_flash_erase(uint32_t addr_start, uint32_t addr_end)
{
    uint32_t addr;

    flash_unlock();

	FLASH->SR |= FLASH_SR_PGAERR | FLASH_SR_PGPERR | FLASH_SR_PGSERR;
	
    // 擦除
    //  for (addr = addr_start; addr <= addr_end; addr += 2048)
    {
        // BOOT 64KB(0~3) + 64KB(4)
        FLASH_Erase_Sector(FLASH_SECTOR_5, FLASH_VOLTAGE_RANGE_3); // 128KB
        FLASH_Erase_Sector(FLASH_SECTOR_6, FLASH_VOLTAGE_RANGE_3); // 128KB
		FLASH_Erase_Sector(FLASH_SECTOR_7, FLASH_VOLTAGE_RANGE_3); // 128KB
    }

    flash_lock();

    return 0;
}
